//
//  KLOrderViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/28.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BLMineOrderViewController.h"
#import "KLOrderHeaderView.h"
#import "KLOrderFooterView.h"
#import "KLOrderTableViewCell.h"
#import "BLOrderModel.h"

#import "BLShopCarRootTableViewCell.h"
#import "BLShopCarHotleCell.h"
#import "BLShopCarPointTableViewCell.h"
#import "BLShopCarBuyTableViewCell.h"
#import "BLShopCarCustomCell.h"


#define shopcallHotelTableViewCellReuserIndetifier @"shopcallHotelTableViewCellReuserIndetifier"
#define shopcallPointTableViewCellReuserIndetifier @"shopcallPointTableViewCellReuserIndetifier"
#define shopcallBuyTableViewCellReuserIndetifier @"shopcallBuyTableViewCellReuserIndetifier"
#define shopcallCustomTableViewCellReuserIndetifier @"shopcallCustomTableViewCellReuserIndetifier"


@interface BLMineOrderViewController ()<STActionSheetDelegate>
@property(nonatomic, assign) NSInteger                     page;
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) STSegementButton                     *segementButton;
@property(nonatomic, strong) STNoresultView                     *noResultView;
@property(nonatomic, strong) NSMutableArray<BLOrderModel*>                     *dataSouce;
@property(nonatomic, strong) BLOrderModel                     *selectedModel;
@property(nonatomic, strong) STButton                     *menuButton;
@end

@implementation BLMineOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _titleArray = @[@"全部",@"待付款",@"待发货",@"待收货",@"已完成"];
    self.title = @"我的订单";
    [self configSubView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (ios11) {
        if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            [self.tableView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2)];
        }
    }
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    
    self.menuButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 70, 44)
                                                title:@"本月账单"
                                           titleColor:BL_BlueBackGroundColor
                                            titleFont:15
                                         cornerRadius:0
                                      backgroundColor:nil
                                      backgroundImage:nil
                                                image:nil];
    
    [self.menuButton  setTitle:@"历史账单" forState:UIControlStateSelected];
    [self st_setRightItemWithView:self.menuButton ];
    
    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, [TMUtils navigationBar].bottom, UIScreenWidth, 44)
                                                         andTitle:_titleArray handle:^(STSegementButton *sender) {
                                                             [weakSelf.tableView.mj_footer endRefreshing];
                                                             [weakSelf.tableView.mj_header beginRefreshing];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = KL_BlueBackGroundColor;
    self.segementButton.butTitleSelectedColor = KL_BlueBackGroundColor;
    self.segementButton.butTitleColor = KL_secendTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    self.segementButton.cureentIndex = 0;
    self.segementButton.autoMoveWithClic = YES;
    [self.view addSubview:self.segementButton];
    
    self.tableView.frame = CGRectMake(0, self.segementButton.bottom, UIScreenWidth, [TMUtils tabbar].top + 49 -self.segementButton.bottom   );
    //无数据view
    self.noResultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 350) title:@"暂无订单" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.noResultView.hidden = YES;
    [self.tableView addSubview:self.noResultView];
    //header
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self sendOrderListRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++ ;
        [self sendOrderListRequest];
    }];
    
    //注册重用
    [self.tableView registerClass:[KLOrderHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    
    [self.tableView registerClass:[KLOrderFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    
    [self.tableView registerClass:[BLShopCarHotleCell class] forCellReuseIdentifier:shopcallHotelTableViewCellReuserIndetifier];
    
    [self.tableView registerClass:[BLShopCarPointTableViewCell class] forCellReuseIdentifier:shopcallPointTableViewCellReuserIndetifier];
    
    [self.tableView registerClass:[BLShopCarBuyTableViewCell class] forCellReuseIdentifier:shopcallBuyTableViewCellReuserIndetifier];
    
    [self.tableView registerClass:[BLShopCarCustomCell class] forCellReuseIdentifier:shopcallCustomTableViewCellReuserIndetifier];
}
- (void)reloadData{
    self.noResultView.hidden = self.dataSouce.count;
    if (self.dataSouce.count >= 10) {
        self.tableView.mj_footer.hidden =NO;
    }else{
        self.tableView.mj_footer.hidden = YES;
    }
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    BLOrderModel * order =  self.dataSouce[section];
    return order.goods.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [BLShopCarPointTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return [KLOrderHeaderView headerHeight];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    KLOrderHeaderView * header = [KLOrderHeaderView new];
    BLOrderModel* model = self.dataSouce[section];
    //1洗涤2定制3积分4采集5私人
    model.indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
    header.model = model;
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [KLOrderFooterView footerHeight];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    KLOrderFooterView * footer = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    footer.model = self.dataSouce[section];
    __weak typeof(self) weakSelf =  self;
    [footer.confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcedMenuButtonWithButton:sender section:section];
    }];
    return footer;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BLOrderModel* model = self.dataSouce[indexPath.section];
    //1洗涤2定制3积分4采集5私人
    model.indexPath = indexPath;
    BLShopCarRootTableViewCell * cell;
    if ([model.goods_type isEqualToString:@"2"]) {
        cell = [tableView dequeueReusableCellWithIdentifier:shopcallHotelTableViewCellReuserIndetifier];
    }else if([model.goods_type isEqualToString:@"3"]){
        cell = [tableView dequeueReusableCellWithIdentifier:shopcallPointTableViewCellReuserIndetifier];
    }else if([model.goods_type isEqualToString:@"4"]){
        cell = [tableView dequeueReusableCellWithIdentifier:shopcallBuyTableViewCellReuserIndetifier];
    }else if([model.goods_type isEqualToString:@"5"]){
        cell = [tableView dequeueReusableCellWithIdentifier:shopcallCustomTableViewCellReuserIndetifier];
    }
    cell.orderModel = model;
    [cell updateConfimUi];
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    BLOrderModel* model = self.dataSouce[indexPath.section];
    if(model.state.integerValue == 1){
        return YES;
    }
    return NO;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self showAlertCancelAndConfirm:@"请问确定要删除订单吗？" andWithBlock:^(NSString *name) {
            if([name isEqualToString:@"确认"]){
                [self sendDelRequestWithIndexPath:indexPath];
            }
        }];
       
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
- (void)st_rightBarAction:(id)sender{
    self.menuButton.selected = !self.menuButton.selected;
    [self.tableView.mj_header beginRefreshing];
}

#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Private Method
- (void)onSelcedMenuButtonWithButton:(UIButton*)button section:(NSInteger)section{
    BLOrderModel * model = self.dataSouce[section];
    self.selectedModel = model;
    if ([button.currentTitle isEqualToString:@"付款"]) {
        
        NSString * paydesc;
        if (model.make_score.integerValue > 0) {
            //积分 + 钱
           paydesc = [NSString stringWithFormat:@"付款%0.2f+%0.2f 积分",
                      [model allMoney].floatValue,
                      [model allpoint].floatValue];
        }else{
            NSString *grade = @"";
            if ([model allGrade].integerValue > 0) {
                grade = [NSString stringWithFormat:@"(赠送盖币%@)",[model allGrade]];
            }
            paydesc = [NSString stringWithFormat:@"付款%0.2f%@",
                                  [model allMoney].floatValue,grade];
        }
        NSString * title1 = [NSString stringWithFormat:@"您将支付宝%@",paydesc];
        NSString * title2 = [NSString stringWithFormat:@"您将微信%@",paydesc];
        NSArray * array = @[title1,title2];
        STActionSheet * sheet = [STActionSheet actionSheetWithTitle:@"支付方式" buttonTitles:array cancelTitle:@"取消" delegate:self];
        [sheet show];
    }
    if ([button.currentTitle isEqualToString:@"确认收货"]) {
        [self sendConfimRequest];
    }
}
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.titleArray.count <= buttonIndex) {
        //点击取消
        return;
    }
    if (buttonIndex == 0) {
        [TMUtils sendAliPayWithOrder:self.selectedModel.oder_nu];
    }
    else{
        [TMUtils sendWechatPayWithOrder:self.selectedModel.oder_nu];
    }
}
- (void)configBLgoodModel:(BLGoodModel*)model array:(NSArray*)jsonArray{
    
//    for (NSDictionary * dic in jsonArray) {
//        if ([dic[@"gid"] isEqualToString:model.goodID]) {
//            model.num = dic[@"num"];
//            if (!model.price.length) {
//                model.price = dic[@"price"];
//            }
//        }
//    }
}
#pragma mark --NetWork Method
- (void)sendOrderListRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/orderAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [dic setObject:@(self.page) forKey:@"page"];
    NSArray * array =  _titleArray;
    NSString * title =  array[self.segementButton.cureentIndex];
    NSInteger num  = [array indexOfObject:title] ;
    [dic setObject:@(num) forKey:@"state"];
    
    if (self.menuButton.selected) {
        [dic setObject:@"1" forKey:@"type"];
    }else{
         [dic setObject:@"0" forKey:@"type"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"][@"order"];
                                                 if (self.page == 1) {
                                                     self.dataSouce = [NSMutableArray new];
                                                     self.selectedModel = nil;
                                                 }
                                                 NSLog(@"json = %@",array.mj_JSONString);
                                                 for (NSDictionary * modelDic in array) {
                                                     BLOrderModel * mdoel = [BLOrderModel mj_objectWithKeyValues:modelDic];
                                                     NSMutableArray * goodArray = [NSMutableArray new];
                                                     NSArray * goodDicArray = modelDic[@"goods"];
                                                     for (NSDictionary * goodDic in goodDicArray) {
                                                         BLGoodModel * goodModel = [BLGoodModel mj_objectWithKeyValues:goodDic];
                                                        
                                                         [goodArray addObject:goodModel];
                                                         
                                                     }
                                                     mdoel.goods = goodArray;
                                                     if (![mdoel.goods_type isEqualToString:@"1"]) {
                                                         [self.dataSouce addObject:mdoel];
                                                     }
                                                     
                                                     
//                                                     NSData *data = [mdoel.json dataUsingEncoding:NSUTF8StringEncoding];
//                                                     if (data) {
//                                                         NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data              options:NSJSONReadingAllowFragments
//                                                                                                                error:nil];
//
//                                                         for (int i = 0; i <mdoel.goods.count; i ++) {
//                                                             BLGoodModel * goodModel =mdoel.goods[i];
//                                                             [self configBLgoodModel:goodModel array:jsonArray];
//                                                         }
//                                                     }

                                                     
                                                     
                                                     
                                                     
                                                 }
                                                 
                                                 [self reloadData];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                 [self reloadData];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendConfimRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/receiptGoodsAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (self.selectedModel.oder_nu.length) {
        [dic setObject:self.selectedModel.oder_nu forKey:@"order_no"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendDelRequestWithIndexPath:(NSIndexPath*)indexPath{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    BLOrderModel* model = self.dataSouce[indexPath.section];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/delOrder"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (model.oder_nu.length) {
        [dic setObject:model.oder_nu forKey:@"oder_nu"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"删除订单成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

